import { Card, Breadcrumb, Form, Input ,Select, Button, message, Radio,Upload} from "antd"
import './index.scss'
import ReactQuill from "react-quill";
import 'react-quill/dist/quill.snow.css'
import {  exitArticleAPI, getArticleDetailsAPI, onSubmitFormAPI } from "@/apis/article";
import { useEffect, useState } from "react";
import { useChannel } from "@/hooks/useChannel";
import { useNavigate, useSearchParams } from "react-router-dom";
const { Option } = Select;
const Pubilsh  = () => {
    const navigate = useNavigate()
    // 获取频道数据逻辑
    const channelList = useChannel()

    const [form] = Form.useForm();
    // 提交表单数据逻辑
    const onFinish = async(formData) => {
    if(imageList.length !== imageType) return message.warning('上传的数量与选择的封面不相匹配')
      const data = {
        title: formData.title,
        content: formData.content,
        cover: { type: imageType, images: imageList.map(item => {
            if(item.response){
                return item.response.data.url
            }else{
                return item.url
            }
        }) },
        channel_id: formData.channel_id
      }
    //   如果有id说明是编辑文章否则是添加文章
     if(articleDetailId){
        await exitArticleAPI({...data, id:articleDetailId})
        message.success('修改文章成功')
        navigate('/article')
     }else{
        await onSubmitFormAPI(data)
        message.success('提交成功')
     }
     
     form.resetFields();
    }
    // 上传图片
    const [ imageList, setImageList ] = useState([])
    const handleChange = (val) => {
       setImageList(val.fileList)
    }
    // 切换文章封面,多图,单图,三图
    const [imageType, setImageType] = useState(0)
    const onTypeRadio = (e) => {
      setImageType(e.target.value)
    }
    // 数据回填的实现
    const [params] = useSearchParams()
    const articleDetailId = params.get('id')
    useEffect(() => { 
         const getArticleDetails = async() => {
            const res = await getArticleDetailsAPI(articleDetailId)
            form.setFieldsValue({...res.data, type: res.data.cover.type})
            // 回填图片列表
            setImageType(res.data.cover.type) //将 type 值传过去有图片的把上传的框显示出来
            setImageList(res.data.cover.images.map((url, idx) => ({ //将图片回显出来(antDengan固定的格式)
                url,
                name: `image${idx}`,
                status: 'done',
                uid: idx + '',
             }))
           )
        }
       if(articleDetailId){ getArticleDetails() } //已进入页面如果能拿到路由跳转id的话
    },[articleDetailId, form])
    return (
        <div className="Publish">
            <Card style={{width: '100%'}} className="pubCard">
                <Breadcrumb items={[{title: <a href="/">首页</a>},{title: articleDetailId ? '编辑文章' : '发布文章'}]}/>
                    {/* 表单 */}
                <Form form={form} className="pubForm" validateTrigger='onBlur' onFinish={onFinish} initialValues={{type: 0}}>
                    {/* 标题 */}
                    <Form.Item 
                        wrapperCol={{span: 16}}
                        label='标题' 
                        name='title' 
                        rules={[{ required: true, message: '请输入标题' }]}>
                        <Input placeholder="请输入标题" ></Input>
                    </Form.Item>
                    {/* 频道 */}
                    <Form.Item 
                        wrapperCol={{span: 16}} 
                        name="channel_id" 
                        label="频道" 
                        rules={[{ required: true, message: '请选择频道' }]}>
                        <Select placeholder="请选择你喜欢的频道" >
                          {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option> )}
                        </Select>
                    </Form.Item>
                    {/* 封面 */}
                    <Form.Item label='封面'>
                        {/* 单选按钮 */}
                       <Form.Item name="type">
                            <Radio.Group onChange={onTypeRadio} >
                                <Radio value={0}>无图</Radio>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                            </Radio.Group>
                       </Form.Item>
                        {/* 上传图片 */}
                        { imageType !== 0 && <Form.Item>
                            <Upload  
                                name="image"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList
                                action="http://geek.itheima.net/v1_0/upload"
                                fileList={imageList}
                                maxCount={imageType}
                                onChange={handleChange}>
                                <div>+</div>
                            </Upload>
                        </Form.Item>}
                    </Form.Item>
                    {/* 内容 */}
                     <Form.Item 
                        name="content" 
                        label="内容" 
                        rules={[{ required: true, message: '请选择频道' }]}>
                        <ReactQuill 
                          className="publishQuill"
                          placeholder="请输入你喜欢的内容" 
                          theme="snow"/>
                    </Form.Item>
                    {/* 提交按钮 */}
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">发布文章</Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}
export default Pubilsh